#include "flash.h"
#include "record.h"

#define	SPACE	0xffffffff

static uint *record_bottom;
static uint	*record_head;
static uint	record_steps;
static uint	record_tick;
static uint *record_top;

static void put(uint value){
	flash_put32(record_head,value);
	record_head++;
	if(record_head>record_top)
		record_head=record_bottom;
}

//------------------------------------------------------------------------------

void record_init(void* bottom,void* vect){
	uint *p=(uint*)bottom+1;
	record_bottom=p;
	record_top=record_bottom+0x7800/sizeof(uint);
	if(*(p-1)==SPACE){
		while(*p==SPACE && p<=record_top)
			p++;
		if(p<=record_top)while(*p!=SPACE && p<=record_top)
			p++;
		if(p>record_top)
			p=record_bottom;
	}else{
		flash_begin();
		uint* a=0;
		uint* b=(uint*)vect;
		uint* c=(uint*)256;
		while(a<c)if(*a++!=*b++){
			flash_erasePage(a);
			flash_copy(0,vect,1024);
			break;
		}
		flash_erasePage(p);
		flash_erasePage(p+1024/sizeof(uint));
		flash_end();
	}
	record_head=p;
}
void record_roll(void){
	uint *p=record_head;
	while(*p==SPACE && p<=record_top)
		p++;
	if(p>record_top){
		p=record_bottom;
		while(*p==SPACE && p<record_head)
			p++;
	}
	uint s=p-record_head;
	if(p<record_head)
		s+=0x7800;
	if(s<2048){
		flash_begin();
		while(s<2048){
			flash_erasePage(p);
			p+=1024/sizeof(uint);
			if(p>record_top)
				p=record_bottom;
			s+=1024;
		}
		flash_end();
	}
}
void record_save(uint tick,uint steps){
	if(record_head && (steps!=record_steps)){
		flash_begin();
		uint t=tick-record_tick;
		uint v=steps-record_steps;
		record_tick=tick;
		record_steps=steps;
		if(t>0xffff)
			put(tick>0xffff?tick:0xffff0000+tick);
		else v+=t<<16;
		put(v);
		flash_end();
	}
}